
//  QainliUserDetail.swift
//  todoios
//
//  Created by qianli on 2025/5/21.
//

import Foundation
import SwiftyUserDefaults
import SVGKit

class QainliUserDetail: QianliParentNaviVC {
    private var yYfZnCKFmQRnxYeI:UIImageView=UIImageView()
    private var jXpbrxMcMxCQdsDc:UILabel?
    private var ai6G1Cet7mWYFD4V:UILabel?
    private var ZYRF5ZPyDdU9kORK:UILabel?
    
    private var rG0bPuFNG6wJFOou: GradientBtn?
    private var OPTiRSiTj7Re3bBC: GradientBtn?
    private var APvkXf5TaubkoBI3: GradientBtn?
    private var hAiuOAbXV3bS5LXQ: UIButton?
    
    private var ij6UhR5tzZ2FlY8u:[UIImageView] = []
    private var QcbgD7fvbwU7teJt:[UILabel] = []
    private var pIl7wVZ66Bx6slLe:[UIButton] = []
    
    private var mHMReGA31jq6SbTY:MBProgressHUD?
    
    override func GHL4Rhb91XYBer27(){
        self.zdMpsGrNncVEHdYA(title: LocalizedString("ACCOUNT INFO"))
        
        let userRowHeight = 100.0
        let titleBar = UIView(frame: CGRect(x: 15, y: topSpace+15, width: qianli_pm_width-30, height: userRowHeight))
        self.view.addSubview(titleBar)
        titleBar.backgroundColor = .systemBackground
        titleBar.layer.cornerRadius = 10
        
        let avatarWidth = 70.0
        let itop = userRowHeight/2 - avatarWidth/2
        
        titleBar.addSubview(self.yYfZnCKFmQRnxYeI)
        self.yYfZnCKFmQRnxYeI.frame = CGRect(x: 15, y: itop, width: avatarWidth, height: avatarWidth)
        self.yYfZnCKFmQRnxYeI.layer.cornerRadius = avatarWidth / 2
        self.yYfZnCKFmQRnxYeI.clipsToBounds = true
        self.yYfZnCKFmQRnxYeI.qianli_image(imgurl: "qianliLoading.gif")
        self.GXwrjdpULOsWeoiB(avatar: Defaults[\.avatar])
     
        
        
        let contentWidth = titleBar.bounds.width
        let iLeft = 15+avatarWidth+10
        self.jXpbrxMcMxCQdsDc = UILabel(frame: CGRect(x: iLeft, y: itop, width: contentWidth-iLeft-10, height: 25))
        if let labeluser = self.jXpbrxMcMxCQdsDc{
            titleBar.addSubview(labeluser)
            labeluser.textColor = .label
            labeluser.font = .systemFont(ofSize: 16)
            labeluser.text = Defaults[\.username]
        }

        self.ai6G1Cet7mWYFD4V = UILabel(frame: CGRect(x: iLeft, y: itop+30, width: contentWidth-iLeft-10, height: 20))
        if let lbvip = self.ai6G1Cet7mWYFD4V{
            titleBar.addSubview(lbvip)
            lbvip.textColor = .secondaryLabel
            lbvip.font = .systemFont(ofSize: 13)
            let myLevel = Defaults[\.memberLevel]
            let levelStr = "\(LocalizedString("MEMBER LEVEL"))：" + QianliUtils.shared.getLevel(level:myLevel)
            HaBjqrPksgDI8DHj(on: lbvip, with: levelStr, and: "\(LocalizedString("MEMBER LEVEL"))：", and: 13.0)
        }
        
        self.ZYRF5ZPyDdU9kORK = UILabel(frame: CGRect(x: iLeft, y: itop+55, width: contentWidth-iLeft-10, height: 15))
        if let labelTime = self.ZYRF5ZPyDdU9kORK{
            titleBar.addSubview(labelTime)
            labelTime.textColor = .secondaryLabel
            labelTime.font = .systemFont(ofSize: 13)
            if !Defaults[\.memberexpiryat].isEmpty{
               let iso8601String = Defaults[\.memberexpiryat]
               let formatTime = "\(LocalizedString("EXPIRE TIME"))：" + isoDate2Formatdate(iso8601String)
                HaBjqrPksgDI8DHj(on: labelTime, with: formatTime, and: "\(LocalizedString("EXPIRE TIME"))：", and: 13.0)
            }else{
                labelTime.text = "\(LocalizedString("EXPIRE TIME"))：xxxx-xx-xx xx:xx:xx"
            }
        }
        let labelTS = UILabel(frame: CGRect(x: 15, y: titleBar.frame.maxY+15.0, width: qianli_pm_width-30, height: 30))
        view.addSubview(labelTS)
        labelTS.text = "- 设备管理 -"
        labelTS.textColor = .secondaryLabel
        labelTS.textAlignment = .center
        labelTS.font = .systemFont(ofSize: 12)
        
        let deviceView = UIView(frame: CGRect(x: 15, y: labelTS.frame.maxY, width: qianli_pm_width-30, height: 300))
        view.addSubview(deviceView)
        deviceView.backgroundColor = .systemBackground
        deviceView.layer.cornerRadius = 10
        
        let ico_1 = UIImageView(frame: CGRect(x: 15, y: 100/2-50/2, width: 50, height: 50))
        deviceView.addSubview(ico_1)
        ico_1.image = "qianli_bindevice_blue".qianli_R_image
        self.ij6UhR5tzZ2FlY8u.append(ico_1)
        
        let label_1 = UILabel(frame: CGRect(x: 15+50+10, y: 100/2-50/2, width: deviceView.bounds.width-15-50-10-90, height: 50))
        deviceView.addSubview(label_1)
        label_1.font = .systemFont(ofSize: 15)
        label_1.textColor = .label
        label_1.text = QianliUtils.shared.getDeviceId()  // "iOS-8EB6FB0B-831F-446E-9EB8-D88BB6587830"
        label_1.numberOfLines = 0
        self.QcbgD7fvbwU7teJt.append(label_1)
        
        let btn_1 = UIButton(frame: CGRect(x: deviceView.bounds.width-15-65, y: 100/2-36/2, width: 65, height: 36))
        deviceView.addSubview(btn_1)
        btn_1.setTitle(LocalizedString("LOCAL"), for: .normal)
        btn_1.setTitleColor(.secondaryLabel, for: .normal)
        btn_1.titleLabel?.font = .systemFont(ofSize: 14)
        btn_1.layer.cornerRadius = 18
        self.pIl7wVZ66Bx6slLe.append(btn_1)
        btn_1.touch_With_Block { [weak self] sender in
            if let self = self{
                self.OViHf8HqtY3ULCUH(itag: sender.tag)
            }
        }
        
        var halfTop = 100.0
        let ico_2 = UIImageView(frame: CGRect(x: 15, y:halfTop + 100/2 - 50/2, width: 50, height: 50))
        deviceView.addSubview(ico_2)
        ico_2.image = "qianli_bindevice_gray".qianli_R_image
        self.ij6UhR5tzZ2FlY8u.append(ico_2)
        
        let label_2 = UILabel(frame: CGRect(x: 15+50+10, y:halfTop + 100/2 - 50/2, width: deviceView.bounds.width-15-50-10-90, height: 50))
        deviceView.addSubview(label_2)
        label_2.font = .systemFont(ofSize: 15)
        label_2.textColor = .secondaryLabel
        label_2.text = LocalizedString("Can Bind")
        label_2.numberOfLines = 0
        self.QcbgD7fvbwU7teJt.append(label_2)
        
        let btn_2 = UIButton(frame: CGRect(x: deviceView.bounds.width-15-65, y:halfTop + 100/2 - 36/2, width: 65, height: 36))
        deviceView.addSubview(btn_2)
        btn_2.setTitle(LocalizedString("UNBIND"), for: .normal)
        btn_2.setTitleColor(.white, for: .normal)
        btn_2.backgroundColor = UIColor("#3366FF")
        btn_2.titleLabel?.font = .systemFont(ofSize: 14)
        btn_2.layer.cornerRadius = 18
        btn_2.isHidden = true
        self.pIl7wVZ66Bx6slLe.append(btn_2)
        btn_2.touch_With_Block {[weak self] sender in
            if let self = self{
                self.OViHf8HqtY3ULCUH(itag: sender.tag)
            }
        }
        
        halfTop = 200.0
        let ico_3 = UIImageView(frame: CGRect(x: 15, y:halfTop + 100/2 - 50/2, width: 50, height: 50))
        deviceView.addSubview(ico_3)
        ico_3.image = "qianli_bindevice_gray".qianli_R_image
        self.ij6UhR5tzZ2FlY8u.append(ico_3)
        
        let label_3 = UILabel(frame: CGRect(x: 15+50+10, y:halfTop + 100/2 - 50/2, width: deviceView.bounds.width-15-50-10-90, height: 50))
        deviceView.addSubview(label_3)
        label_3.font = .systemFont(ofSize: 15)
        label_3.textColor = .secondaryLabel
        label_3.text = LocalizedString("Can Bind")
        label_3.numberOfLines = 0
        self.QcbgD7fvbwU7teJt.append(label_3)
        
        let btn_3 = UIButton(frame: CGRect(x: deviceView.bounds.width-15-65, y:halfTop + 100/2 - 36/2, width: 65, height: 36))
        deviceView.addSubview(btn_3)
        btn_3.setTitle(LocalizedString("Upgrade Now"), for: .normal) //UNBIND
        btn_3.setTitleColor(.white, for: .normal)
        btn_3.backgroundColor = UIColor("#3366FF")
        btn_3.titleLabel?.font = .systemFont(ofSize: 14)
        btn_3.layer.cornerRadius = 18
        btn_3.isHidden = true
        self.pIl7wVZ66Bx6slLe.append(btn_3)
        btn_3.touch_With_Block {[weak self] sender in
            if let self = self{
                self.OViHf8HqtY3ULCUH(itag: sender.tag)
            }
        }
        
        let lineH = CALayer() //分隔线
        deviceView.layer.addSublayer(lineH)
        lineH.frame = CGRect(x: 15, y: 100, width: deviceView.bounds.width-30, height: 0.5)
        lineH.backgroundColor = UIColor.systemGray.withAlphaComponent(0.5).cgColor
        
        let lineH2 = CALayer() //分隔线
        deviceView.layer.addSublayer(lineH2)
        lineH2.frame = CGRect(x: 15, y: 200, width: deviceView.bounds.width-30, height: 0.5)
        lineH2.backgroundColor = UIColor.systemGray.withAlphaComponent(0.5).cgColor
        
//判断是否登录,已登录，则显示退出登录，未登录，则显示注册和登录
        let iMid = qianli_pm_width/2
        let iTop = qianli_pm_height-150
        
        //------ 登录及注册
        self.rG0bPuFNG6wJFOou = GradientBtn(frame: CGRect(x: iMid-15-120, y: iTop, width: 120, height: 40), title: LocalizedString("LOGIN"))
        if let loginbtn = self.rG0bPuFNG6wJFOou{
            view.addSubview(loginbtn)
            loginbtn.touch_With_Block { [weak self]sender in
                QianliVibrateEnum.light.vibrate()
                if let self = self{
                    self.UWRdl1krZEkBno2y()
                }
            }
            loginbtn.isHidden = true
        }
        
        self.OPTiRSiTj7Re3bBC = GradientBtn(frame: CGRect(x: iMid+15, y: iTop, width: 120, height: 40), title: LocalizedString("REGISTER"))
        if let rgbtn = self.OPTiRSiTj7Re3bBC{
            view.addSubview(rgbtn)
            rgbtn.touch_With_Block { [weak self]sender in
                QianliVibrateEnum.light.vibrate()
                if let self = self{
                    self.ph2lqG56246k5nHN()
                }
            }
            rgbtn.isHidden = true
        }
        
        //------ 退出登录及注销
        self.APvkXf5TaubkoBI3 = GradientBtn(frame: CGRect(x: iMid-100, y: iTop, width: 200, height: 40), title: LocalizedString("LOGOUT"))
        if let lgobtn = self.APvkXf5TaubkoBI3{
            view.addSubview(lgobtn)
            lgobtn.touch_With_Block { [weak self]sender in
                QianliVibrateEnum.light.vibrate()
                if let self = self{
                    self.VOtt1iTvhiWDO5y2()
                }
            }
            lgobtn.isHidden = true
        }
        
        self.hAiuOAbXV3bS5LXQ = UIButton(frame: CGRect(x: iMid-100, y: iTop+40+15, width: 200, height: 40))
        if let deabtn = self.hAiuOAbXV3bS5LXQ{
            view.addSubview(deabtn)
            deabtn.setTitle(LocalizedString("DELETE ACCOUNT"), for: .normal)
            deabtn.setTitleColor(.label, for: .normal)
            deabtn.titleLabel?.font = .systemFont(ofSize: 15)
            deabtn.touch_With_Block { [weak self] sender in
                QianliVibrateEnum.light.vibrate()
                if let self = self{
                    self.WmYjVamD9rmQGZox()
                }
            }
            deabtn.isHidden = true
        }
        
        VeXogmVun9c0uHtp()
        
        let labelTips = UILabel(frame: CGRect(x: 15, y: iTop-40-20, width: qianli_pm_width-30, height: 40))
        view.addSubview(labelTips)
        labelTips.font = .systemFont(ofSize: 13)
        labelTips.textColor = .secondaryLabel
        labelTips.text = LocalizedString("ACCOUNT DEVICE INFO") //"一个账号目前最多支持两个设备，暂时不能解锁更多的设备，此功能会在后续版本推出，敬请期待！"
        labelTips.numberOfLines = 0
        labelTips.textAlignment = .center
        
    }
    
    override func aB7kFqI8MB6DRPQC() {
        self.wbHTV08F4lRCXVBW()
    }
}


extension QainliUserDetail{
    private func HaBjqrPksgDI8DHj(on label:UILabel,with newTitle:String,and normalText:String,and fontsize:CGFloat){
//富文本
        let myMutableString = NSMutableAttributedString(
                    string: newTitle,
                    attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: fontsize),
                                 NSAttributedString.Key.foregroundColor:UIColor(hexString: "#3964ff")])
        let range_N:NSRange = (newTitle as NSString).range(of:normalText)
        myMutableString.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.secondaryLabel], range: range_N)
        label.attributedText = myMutableString
    }
    
    private func GXwrjdpULOsWeoiB(avatar:String){
        if avatar.isEmpty{
            self.yYfZnCKFmQRnxYeI.image = "qianli_placeholder".qianli_R_image
            return
        }
        if let imageUrl = URL(string: LoginViewModel.shared.url_JKou + avatar){
            if imageUrl.pathExtension.lowercased() == "svg" { //svg类型图标特殊处理
//              imgHeader.image =  SVGKImage(contentsOf: imageUrl).uiImage //同步加载SVG图片
                let task = URLSession.shared.dataTask(with: imageUrl) { (data, response, error) in
                            if let error = error {
                                QianliUniversalFunc.QianliLog("Error loading image: \(error)")
                                DispatchQueue.main.async {[weak self] in
                                    if let self = self{
                                        self.yYfZnCKFmQRnxYeI.image = "qianli_placeholder".qianli_R_image
                                         
                                    }
                                }
                                return
                            }

                            guard let data = data else {
                                QianliUniversalFunc.QianliLog("No data received")
                                DispatchQueue.main.async {[weak self] in
                                    if let self = self{
                                        self.yYfZnCKFmQRnxYeI.image = "qianli_placeholder".qianli_R_image
                                        
                                    }
                                }
                                return
                            }

                            // 在后台线程解析 SVG 数据
                            DispatchQueue.global().async {
                                if let svgImage = SVGKImage(data: data) {
                                    let uiImage = svgImage.uiImage
                                    DispatchQueue.main.async {[weak self] in
                                        if let self = self{
                                                self.yYfZnCKFmQRnxYeI.image = uiImage
                                            
                                        }
                                    }
                                }
                            }
                        }
                        // 启动任务
                        task.resume()
            }else{
                self.yYfZnCKFmQRnxYeI.sd_setImage(with: imageUrl, placeholderImage: nil) { [weak self](image, error, cacheType, url) in
                    if error != nil || image == nil{
                        if let self = self{
                            self.yYfZnCKFmQRnxYeI.image = "qianli_placeholder".qianli_R_image
                        }
                    }
                }
            }
        }else{
            self.yYfZnCKFmQRnxYeI.image = "qianli_placeholder".qianli_R_image
        }
    }
}

extension QainliUserDetail{
    private func xZaSOTEy3nG6hSr3(_ errmsg:String){
        self.Lh8UixDTUCV7ruEB(false)
        self.alert_qianli_message(LocalizedString("Friendly Reminder"), message: "\(errmsg)\n\(LocalizedString("Please login again!"))") {[weak self] in
            if let self = self{
                self.UWRdl1krZEkBno2y()
            }
        }
    }
    
//获取设备列表
    @objc func wbHTV08F4lRCXVBW(){
        UserInfoViewModel.shared.JOxbbBuNr3loTKi4 { result in
            DispatchQueue.main.async {[weak self] in
                if let self = self{
                    switch result{
                    case .success(let baseData):
                        if baseData.code == 0{
                            self.IKAOnJFe4M5nh6eP("")
                        }else if baseData.code == 40101{
                            self.xZaSOTEy3nG6hSr3(baseData.msg)
                        }else{
                            self.IKAOnJFe4M5nh6eP(baseData.msg)
                        }
                    case .failure(let err):
                        self.IKAOnJFe4M5nh6eP(err.localizedDescription)
                        
                    }
                }
            }
        }
    }
    
    func IKAOnJFe4M5nh6eP(_ errMsg:String){
        if (errMsg.isEmpty){
            if let userDeviceList = UserInfoViewModel.shared.userDeviceList{
                let current_device_id = userDeviceList.current
                if let data = userDeviceList.data{
                    print("showDeviceList:\(data)")
                    var i=0
                    for device in data{//居然空值返回，返回4个data,但只有第1个data里有device_id
                        let device_id = device.device_id
                        if !device_id.isEmpty{
                            self.QcbgD7fvbwU7teJt[i].text = device_id
                            if(device_id.lowercased() == current_device_id.lowercased()){
                                self.ij6UhR5tzZ2FlY8u[i].image = "qianli_bindevice_blue".qianli_R_image
                                self.pIl7wVZ66Bx6slLe[i].setTitle(LocalizedString("LOCAL"), for: .normal)
                                self.pIl7wVZ66Bx6slLe[i].setTitleColor(.secondaryLabel, for: .normal)
                                self.pIl7wVZ66Bx6slLe[i].backgroundColor = .systemBackground
                                self.pIl7wVZ66Bx6slLe[i].isHidden = false
                                self.pIl7wVZ66Bx6slLe[i].isEnabled = false
                            }else{
                                self.ij6UhR5tzZ2FlY8u[i].image = "qianli_bindevice_blue".qianli_R_image
                                self.pIl7wVZ66Bx6slLe[i].setTitle(LocalizedString("UNBIND"), for: .normal)
                                self.pIl7wVZ66Bx6slLe[i].setTitleColor(.white, for: .normal)
                                self.pIl7wVZ66Bx6slLe[i].backgroundColor = UIColor("#3366FF")
                                self.pIl7wVZ66Bx6slLe[i].isHidden = false
                                self.pIl7wVZ66Bx6slLe[i].isEnabled = true
                                self.pIl7wVZ66Bx6slLe[i].tag = i
                            }
                            i += 1
                        }
                        if i>=3{
                            break
                        }
                    }
                    
                    if i<2{ //只绑定了1个设备,第2个显示可绑定
                        self.QcbgD7fvbwU7teJt[1].text = LocalizedString("Can Bind")
                        self.ij6UhR5tzZ2FlY8u[1].image = "qianli_bindevice_gray".qianli_R_image
                        self.pIl7wVZ66Bx6slLe[1].isHidden = true
                        self.pIl7wVZ66Bx6slLe[1].isEnabled = false
                    }
                    
                    let maxCount = Defaults[\.maxBindCount]
                    if maxCount==2{ //只能绑定2台设备，则第3台为升级后绑定
                        self.QcbgD7fvbwU7teJt[2].text = LocalizedString("Premium Member Can Bind")
                        self.ij6UhR5tzZ2FlY8u[2].image = "qianli_bindevice_gray".qianli_R_image
                        self.pIl7wVZ66Bx6slLe[2].isHidden = false
                        self.pIl7wVZ66Bx6slLe[2].setTitle(LocalizedString("Upgrade Now"), for: .normal)
                        self.pIl7wVZ66Bx6slLe[2].isEnabled = true
                        self.pIl7wVZ66Bx6slLe[2].tag = 9
                    }else if maxCount>2{//可绑定3台，
                        if i<3{//并且第3台是未绑定状态,显示可绑定
                            self.QcbgD7fvbwU7teJt[2].text = LocalizedString("Can Bind")
                            self.ij6UhR5tzZ2FlY8u[2].image = "qianli_bindevice_gray".qianli_R_image
                            self.pIl7wVZ66Bx6slLe[2].isHidden = true
                            self.pIl7wVZ66Bx6slLe[2].setTitle(LocalizedString("UNBIND"), for: .normal)
                            self.pIl7wVZ66Bx6slLe[2].isEnabled = false
                        }
                    }
                    
                    self.WXMa13U1d5HrY5jB("bind")
                    
                    return
                }
            }
        }else{
            self.view.Qianli_Toast(errMsg)
        }
        //获取绑定出错状态下显示
        self.QcbgD7fvbwU7teJt[0].text = LocalizedString("Can Bind")
        self.ij6UhR5tzZ2FlY8u[0].image = "qianli_bindevice_gray".qianli_R_image
        self.pIl7wVZ66Bx6slLe[0].isHidden = true
        self.pIl7wVZ66Bx6slLe[0].isEnabled = false
        
        self.QcbgD7fvbwU7teJt[1].text = LocalizedString("Can Bind")
        self.ij6UhR5tzZ2FlY8u[1].image = "qianli_bindevice_gray".qianli_R_image
        self.pIl7wVZ66Bx6slLe[1].isHidden = true
        self.pIl7wVZ66Bx6slLe[1].isEnabled = false
        let iMax = Defaults[\.maxBindCount]
        if iMax>2{ //可绑定
            self.QcbgD7fvbwU7teJt[2].text = LocalizedString("Can Bind")
            self.ij6UhR5tzZ2FlY8u[2].image = "qianli_bindevice_gray".qianli_R_image
            self.pIl7wVZ66Bx6slLe[2].isHidden = true
            self.pIl7wVZ66Bx6slLe[2].setTitle(LocalizedString("UNBIND"), for: .normal)
            self.pIl7wVZ66Bx6slLe[2].isEnabled = false
        }else if iMax==2{ //可升级
            self.QcbgD7fvbwU7teJt[2].text = LocalizedString("Premium Member Can Bind")
            self.ij6UhR5tzZ2FlY8u[2].image = "qianli_bindevice_gray".qianli_R_image
            self.pIl7wVZ66Bx6slLe[2].isHidden = false
            self.pIl7wVZ66Bx6slLe[2].setTitle(LocalizedString("Upgrade Now"), for: .normal)
            self.pIl7wVZ66Bx6slLe[2].isEnabled = true
            self.pIl7wVZ66Bx6slLe[2].tag = 9
        }
        
    }
    
    private func AQJHyT4esgZZcrFd(){
        let memberVC = QianliMemberVC()
        memberVC.modalPresentationStyle = .overFullScreen
        self.present(memberVC, animated: true)
        memberVC.dismissBlock = {[weak self] in
//重新拉取用户信息，
            self?.MuIZuRZXjs2PfsXX()
            self?.wbHTV08F4lRCXVBW()
        }
    }
    
    private func MuIZuRZXjs2PfsXX(){
        self.yYfZnCKFmQRnxYeI.qianli_image(imgurl: "qianliLoading.gif")
        self.M62h1bVOydwY8i4y("")
        UserInfoViewModel.shared.MuIZuRZXjs2PfsXX { result in
            DispatchQueue.main.async {[weak self] in
                self?.l0JOXR3PG9RznwqZ()
                switch result{
                case .success(let baseData):
                    if baseData.code == 0{
                        self?.uPJoek6ybNz2kTSg(false)
                    }else if baseData.code == 40101{
                        self?.xZaSOTEy3nG6hSr3(baseData.msg)
                    } else{
                        self?.GXwrjdpULOsWeoiB(avatar: Defaults[\.avatar])
                        self?.view.Qianli_Toast("[\(baseData.code)]\(baseData.msg)")
                    }
                case .failure(let err):
                    self?.view.Qianli_Toast(err.localizedDescription)
                }
            }
        }
    }
    
    
    private func OViHf8HqtY3ULCUH(itag:Int){
        QianliVibrateEnum.light.vibrate()
//询问是否要解绑该设备
        if itag == 9{
            //升级会员
            self.AQJHyT4esgZZcrFd()
        }
        else if itag<=2{
            self.alert_qianli_message(LocalizedString("Unbind Device"), message: LocalizedString("Sure to unbind this device?"),iRed: false) {[weak self] in
                if let self = self{
                    self.M62h1bVOydwY8i4y("")
                    if let deviceId = self.QcbgD7fvbwU7teJt[itag].text{
                        UserInfoViewModel.shared.ofuUSDfMhcfgsObm(deviceId: deviceId) { result in
                            DispatchQueue.main.async {[weak self] in
                                if let self = self{
                                    switch result{
                                    case .success(let baseData):
                                        if baseData.code == 0{
                                            self.tJGZiaPO8mGp5cyS("")
                                        }else{
                                            self.tJGZiaPO8mGp5cyS(baseData.msg)
                                        }
                                    case .failure(let error):
                                        self.tJGZiaPO8mGp5cyS(error.localizedDescription)
                                    }
                                }
                            }
                        }
                    }
                }
                
                
            }
        }
    }
    
    private func tJGZiaPO8mGp5cyS(_ errmsg:String){
        self.l0JOXR3PG9RznwqZ()
        if errmsg.isEmpty{
            self.perform(#selector(wbHTV08F4lRCXVBW), with: nil, afterDelay: 0.5)
        }else{
            self.view.Qianli_Toast(errmsg)
        }
    }
}

extension QainliUserDetail{
    private func VOtt1iTvhiWDO5y2(){
        self.alert_qianli_message(LocalizedString("ADMIN NOTICE"), message: "\n"+LocalizedString("LOGOUT INFO"),iRed: false) {[weak self] in
            if let self = self{
                self.Lh8UixDTUCV7ruEB(true)
            }
        }
    }
//    登录、注册、退出登录、注销
    private func UWRdl1krZEkBno2y(){
        let loginVc = QainliUserLoginVC()
        loginVc.modalPresentationStyle = .overFullScreen
        loginVc.loginOKBlock = {[weak self] in
        //登录成功后，要更新详情信息
            if let self = self{
                DispatchQueue.main.async {
                    self.view.Qianli_Toast(LocalizedString("Login Success!"))
                    self.uPJoek6ybNz2kTSg(false)
                }
            }
        }
        self.present(loginVc, animated: true)
    }
    
    private func ph2lqG56246k5nHN(){
        let registerVc = QianliUserRegisterVC()
        registerVc.modalPresentationStyle = .overFullScreen
        registerVc.registerOKBlock = {[weak self]mail,pw in
            if let self = self{
                self.X7vYe1QunkSRgBBp("")
            }
        }
        
        self.present(registerVc, animated: true)
    }
    
    private func ohye52Si8Tbit5fd(_ s_mail:String,_ s_pw:String){
        self.M62h1bVOydwY8i4y(LocalizedString("Register successful! Loading info, please wait...."))
        
        let deviceId = getDeviceID()
        let lgRequest = LoginRequest(device_id: deviceId, email_code: "", password: s_pw, user_name: s_mail)
        LoginViewModel.shared.PToBQUrjD0wWrDlk(loginRequest: lgRequest) { result in
            DispatchQueue.main.async { [weak self] in
                if let self = self{
                    switch result {
                    case .success(let loginResults):
                        if loginResults.code != 0 {
                            self.X7vYe1QunkSRgBBp(loginResults.msg)
                        }else if let _ = loginResults.data{
                            LoginViewModel.shared.isLogouted = false
                            self.X7vYe1QunkSRgBBp("")
                        }else{
                            self.X7vYe1QunkSRgBBp("\(LocalizedString("Load Failed"))：\(LocalizedString("Invalid user data"))")
                        }
                    case .failure(let error):
                        self.X7vYe1QunkSRgBBp("\(LocalizedString("Load Failed"))：\(error.localizedDescription)")
                    }
                }
            }
        }
    }
    
    private func X7vYe1QunkSRgBBp(_ msg:String){
        self.l0JOXR3PG9RznwqZ()
        
        if (msg.isEmpty){
            LoginViewModel.shared.isLogouted = false
//更新用户信息+绑定设备信息
            self.uPJoek6ybNz2kTSg(false)
            self.view.Qianli_Toast(LocalizedString("Loading succeeded, enjoy it!"))
        }else{
            self.view.Qianli_Toast(msg)
        }
    }
    
    
    
    private func VeXogmVun9c0uHtp(){
        let isguest = Defaults[\.isGuset]
        if (isguest){
            if let loginbtn = self.rG0bPuFNG6wJFOou{
                loginbtn.isHidden = false
            }
            if let rgbtn = self.OPTiRSiTj7Re3bBC{
                rgbtn.isHidden = false
            }
            if let lgobtn = self.APvkXf5TaubkoBI3{
                lgobtn.isHidden = true
            }
            if let deabtn = self.hAiuOAbXV3bS5LXQ{
                deabtn.isHidden = true
            }
        }else{
            if let lgobtn = self.APvkXf5TaubkoBI3{
                lgobtn.isHidden = false
            }
            if let deabtn = self.hAiuOAbXV3bS5LXQ{
                deabtn.isHidden = false
            }
            if let loginbtn = self.rG0bPuFNG6wJFOou{
                loginbtn.isHidden = true
            }
            if let rgbtn = self.OPTiRSiTj7Re3bBC{
                rgbtn.isHidden = true
            }
        }
    }
    
    private func uPJoek6ybNz2kTSg(_ isReset:Bool = false){
        VeXogmVun9c0uHtp()
        if (isReset){
            if let labeluser = self.jXpbrxMcMxCQdsDc{
                labeluser.text = "尚未登录"
            }
            if let lbvip = self.ai6G1Cet7mWYFD4V{
                lbvip.text =  "\(LocalizedString("MEMBER LEVEL"))：尚未登录"
            }
            self.yYfZnCKFmQRnxYeI.image = "qianli_slider_guesthead".qianli_R_image
            if let labelTime = self.ZYRF5ZPyDdU9kORK{
                labelTime.text = "\(LocalizedString("EXPIRE TIME"))：xxxx-xx-xx xx:xx:xx"
            }
        }else{
            if let labeluser = self.jXpbrxMcMxCQdsDc{
                labeluser.text = Defaults[\.username]
            }
            if let lbvip = self.ai6G1Cet7mWYFD4V{
                let myLevel = Defaults[\.memberLevel]
                let levelStr = "\(LocalizedString("MEMBER LEVEL"))：" + QianliUtils.shared.getLevel(level:myLevel)
                self.HaBjqrPksgDI8DHj(on: lbvip, with: levelStr, and: "\(LocalizedString("MEMBER LEVEL"))：", and: 13.0)
            }
            
            self.GXwrjdpULOsWeoiB(avatar: Defaults[\.avatar])
            if let labelTime = self.ZYRF5ZPyDdU9kORK{
                if !Defaults[\.memberexpiryat].isEmpty{
                    let iso8601String = Defaults[\.memberexpiryat]
                    let formatTime = "\(LocalizedString("EXPIRE TIME"))：" + isoDate2Formatdate(iso8601String)
                    self.HaBjqrPksgDI8DHj(on: labelTime, with: formatTime, and: "\(LocalizedString("EXPIRE TIME"))：", and: 13.0)
                }else{
                    labelTime.text = "\(LocalizedString("EXPIRE TIME"))：0000-00-00 00:00:00"
                }
            }
        }
        
        //重新加载绑定设备信息
        if !isReset{
            self.wbHTV08F4lRCXVBW()
        }
    }
    
    private func Lh8UixDTUCV7ruEB(_ isBack2Main:Bool){
        let deviceId = getDeviceID()
        if isBack2Main{
            self.M62h1bVOydwY8i4y(LocalizedString("Resetting the environment, please wait..."))
            self.perform(#selector(clFi25NuDNbscWXL), with: nil, afterDelay: 2.0)
        }
        UserInfoViewModel.shared.ofuUSDfMhcfgsObm(deviceId: deviceId) {[weak self] _ in
            Defaults[\.token] = "" //只要响应都清除
            if isBack2Main{
                DispatchQueue.main.async {
                    if let self = self{
                        self.l0JOXR3PG9RznwqZ()
                        self.clFi25NuDNbscWXL()
                    }
                }
            }
        }
        QianliVpnManager.shared.controller?.bMPPOBDIQcRES5Dc()
        Defaults[\.username] = ""
        Defaults[\.avatar] = ""
        Defaults[\.memberexpiryat] = ""
        Defaults[\.invitationCode] = ""
        Defaults[\.memberLevel] = 0
        Defaults[\.isGuset] = true
        Defaults[\.isTester] = false
        Defaults[\.subuuid] = ""
        Defaults[\.maxBindCount] = 2
        
        LoginViewModel.shared.isLogouted = true
        UserInfoViewModel.shared.userDeviceList = nil
        Qianli_G_SharedMdb.shared.SetQianliHealthState(health: "")
        uPJoek6ybNz2kTSg(true)
        mnMPBDuqzrr59PAC()
        
        self.xtryKgMdcxnNWx2B("")
    }
    
    private func mnMPBDuqzrr59PAC(){
        removeUuidYaml()
        Qianli_G_SharedMdb.shared.SetSubUUID(uuid: "")
    }
    
    private func WmYjVamD9rmQGZox(){
        let logoutVc = QianliUserLogoutVC()
        logoutVc.modalPresentationStyle = .overFullScreen
        self.present(logoutVc, animated: true)
        logoutVc.logoutOKBlock = {[weak self] in
            if let self = self{
                self.Km2vfHjxDnmj2agM()
            }
        }
        
    }
    
    private func Km2vfHjxDnmj2agM(){
        self.alert_qianli_message(LocalizedString("ADMIN NOTICE"), message: LocalizedString("Your account has deleted!")) {[weak self] in
            if let self = self{
                self.Lh8UixDTUCV7ruEB(true)
            }
        }
    }
}

extension QainliUserDetail{
    private func xtryKgMdcxnNWx2B(_ msg:String){
        DispatchQueue.main.async {[weak self] in
            if let self = self{
                self.SkIVReuJinPWgtsQ()
                if msg.isEmpty{
                    return
                }
                self.mHMReGA31jq6SbTY = MBProgressHUD.showAdded(to: self.view, animated: true)
                if let detailHud = self.mHMReGA31jq6SbTY,!msg.isEmpty{
                    detailHud.label.text = msg
                }
            }
        }
    }
    private func SkIVReuJinPWgtsQ(){
        if let detailHud = self.mHMReGA31jq6SbTY{
            detailHud.hide(animated: true)
        }
        self.mHMReGA31jq6SbTY = nil
    }
}
